import { QueryClient, QueryCache, MutationCache } from '@tanstack/react-query';

// 查询键工厂
export const queryKeys = {
  // 搜索相关
  search: {
    all: ['search'] as const,
    results: (query: string, filters?: any) => ['search', 'results', query, filters] as const,
    suggestions: (query: string) => ['search', 'suggestions', query] as const,
    trending: () => ['search', 'trending'] as const,
    history: (userId: string) => ['search', 'history', userId] as const,
    stats: (query: string) => ['search', 'stats', query] as const,
  },
  
  // 推荐相关
  recommendations: {
    all: ['recommendations'] as const,
    personalized: (userId: string) => ['recommendations', 'personalized', userId] as const,
    trending: (category?: string) => ['recommendations', 'trending', category] as const,
    similar: (contentId: string) => ['recommendations', 'similar', contentId] as const,
    collaborative: (userId: string) => ['recommendations', 'collaborative', userId] as const,
    contentBased: (userId: string) => ['recommendations', 'content-based', userId] as const,
    hybrid: (userId: string) => ['recommendations', 'hybrid', userId] as const,
    realtime: (userId: string) => ['recommendations', 'realtime', userId] as const,
  },
  
  // 用户相关
  user: {
    all: ['user'] as const,
    profile: (userId: string) => ['user', 'profile', userId] as const,
    preferences: (userId: string) => ['user', 'preferences', userId] as const,
    statistics: (userId: string) => ['user', 'statistics', userId] as const,
    bookmarks: (userId: string) => ['user', 'bookmarks', userId] as const,
    activity: (userId: string) => ['user', 'activity', userId] as const,
  },
  
  // 分析相关
  analytics: {
    all: ['analytics'] as const,
    overview: () => ['analytics', 'overview'] as const,
    trends: (timeRange: string) => ['analytics', 'trends', timeRange] as const,
    performance: () => ['analytics', 'performance'] as const,
  },
} as const;

// 默认查询选项
const defaultQueryOptions = {
  staleTime: 5 * 60 * 1000, // 5分钟
  gcTime: 10 * 60 * 1000, // 10分钟 (原 cacheTime)
  retry: (failureCount: number, error: any) => {
    // API 错误不重试
    if (error?.code?.startsWith('HTTP_4')) {
      return false;
    }
    // 网络错误最多重试3次
    return failureCount < 3;
  },
  retryDelay: (attemptIndex: number) => Math.min(1000 * 2 ** attemptIndex, 30000),
};

// 查询缓存配置
const queryCache = new QueryCache({
  onError: (error, query) => {
    // 全局错误处理
    console.error('Query Error:', {
      queryKey: query.queryKey,
      error,
    });
    
    // 可以在这里添加全局错误通知
    if (typeof window !== 'undefined') {
      window.dispatchEvent(new CustomEvent('query:error', {
        detail: { error, queryKey: query.queryKey }
      }));
    }
  },
  onSuccess: (data, query) => {
    // 查询成功处理
    if (import.meta.env.DEV) {
      console.log('Query Success:', {
        queryKey: query.queryKey,
        data,
      });
    }
  },
});

// 变更缓存配置
const mutationCache = new MutationCache({
  onError: (error, variables, _context, mutation) => {
    // 全局变更错误处理
    console.error('Mutation Error:', {
      mutationKey: mutation.options.mutationKey,
      error,
      variables,
    });
    
    // 可以在这里添加全局错误通知
    if (typeof window !== 'undefined') {
      window.dispatchEvent(new CustomEvent('mutation:error', {
        detail: { error, mutationKey: mutation.options.mutationKey }
      }));
    }
  },
  onSuccess: (data, variables, _context, mutation) => {
    // 变更成功处理
    if (import.meta.env.DEV) {
      console.log('Mutation Success:', {
        mutationKey: mutation.options.mutationKey,
        data,
        variables,
      });
    }
  },
});

// 创建 QueryClient 实例
export const queryClient = new QueryClient({
  queryCache,
  mutationCache,
  defaultOptions: {
    queries: {
      ...defaultQueryOptions,
      refetchOnWindowFocus: false,
      refetchOnReconnect: true,
      refetchOnMount: true,
    },
    mutations: {
      retry: 1,
      retryDelay: 1000,
    },
  },
});

// 查询工具函数
export const queryUtils = {
  // 预取查询
  prefetchQuery: async (queryKey: any[], queryFn: () => Promise<any>) => {
    return queryClient.prefetchQuery({
      queryKey,
      queryFn,
      staleTime: 10 * 60 * 1000, // 预取的数据10分钟内有效
    });
  },
  
  // 设置查询数据
  setQueryData: (queryKey: any[], data: any) => {
    queryClient.setQueryData(queryKey, data);
  },
  
  // 获取查询数据
  getQueryData: (queryKey: any[]) => {
    return queryClient.getQueryData(queryKey);
  },
  
  // 无效化查询
  invalidateQueries: (queryKey: any[]) => {
    return queryClient.invalidateQueries({ queryKey });
  },
  
  // 移除查询
  removeQueries: (queryKey: any[]) => {
    return queryClient.removeQueries({ queryKey });
  },
  
  // 取消查询
  cancelQueries: (queryKey: any[]) => {
    return queryClient.cancelQueries({ queryKey });
  },
  
  // 重置查询
  resetQueries: (queryKey?: any[]) => {
    return queryClient.resetQueries({ queryKey });
  },
  
  // 清除缓存
  clear: () => {
    queryClient.clear();
  },
  
  // 获取缓存统计
  getStats: () => {
    const cache = queryClient.getQueryCache();
    const queries = cache.getAll();
    
    return {
      totalQueries: queries.length,
      activeQueries: queries.filter(q => q.getObserversCount() > 0).length,
      staleQueries: queries.filter(q => q.isStale()).length,
      errorQueries: queries.filter(q => q.state.status === 'error').length,
      loadingQueries: queries.filter(q => q.state.status === 'pending').length,
    };
  },
};

// 离线支持
export const offlineUtils = {
  // 设置离线查询
  setOfflineQuery: (queryKey: any[], data: any) => {
    queryClient.setQueryData(queryKey, data);
    
    // 存储到 localStorage 作为离线备份
    if (typeof window !== 'undefined') {
      try {
        const offlineData = JSON.parse(localStorage.getItem('offline_queries') || '{}');
        offlineData[JSON.stringify(queryKey)] = {
          data,
          timestamp: Date.now(),
        };
        localStorage.setItem('offline_queries', JSON.stringify(offlineData));
      } catch (error) {
        console.warn('Failed to store offline query:', error);
      }
    }
  },
  
  // 获取离线查询
  getOfflineQuery: (queryKey: any[]) => {
    if (typeof window === 'undefined') return null;
    
    try {
      const offlineData = JSON.parse(localStorage.getItem('offline_queries') || '{}');
      const queryData = offlineData[JSON.stringify(queryKey)];
      
      if (queryData) {
        // 检查数据是否过期（24小时）
        const isExpired = Date.now() - queryData.timestamp > 24 * 60 * 60 * 1000;
        if (!isExpired) {
          return queryData.data;
        }
      }
    } catch (error) {
      console.warn('Failed to get offline query:', error);
    }
    
    return null;
  },
  
  // 清除过期的离线数据
  cleanupOfflineData: () => {
    if (typeof window === 'undefined') return;
    
    try {
      const offlineData = JSON.parse(localStorage.getItem('offline_queries') || '{}');
      const now = Date.now();
      const cleanedData: any = {};
      
      Object.entries(offlineData).forEach(([key, value]: [string, any]) => {
        const isExpired = now - value.timestamp > 24 * 60 * 60 * 1000;
        if (!isExpired) {
          cleanedData[key] = value;
        }
      });
      
      localStorage.setItem('offline_queries', JSON.stringify(cleanedData));
    } catch (error) {
      console.warn('Failed to cleanup offline data:', error);
    }
  },
};

// 初始化查询客户端
export function initializeQueryClient() {
  // 清理过期的离线数据
  offlineUtils.cleanupOfflineData();
  
  // 监听网络状态变化
  if (typeof window !== 'undefined') {
    window.addEventListener('online', () => {
      queryClient.resumePausedMutations();
      queryClient.invalidateQueries();
    });
    
    window.addEventListener('offline', () => {
      // 离线时暂停变更
      queryClient.getMutationCache().getAll().forEach(mutation => {
        if (mutation.state.status === 'pending') {
          // React Query 会自动处理离线状态下的变更暂停
          console.log('Mutation paused due to offline status:', mutation.options.mutationKey);
        }
      });
    });
  }
}

// 导出默认实例
export default queryClient;
